﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Diagnostics;
using System.Threading;
using System.Reflection;

namespace EITSurferInfinityLib
{
    /// <summary>
    /// Interaction logic for Settings.xaml
    /// </summary>
    public partial class Settings0 : UserControl
    {
        VirtualDevice Device;
        Dictionary<string, string> dic;
        List<Button> ButtonList;
        List<Button> ButtonColorList;
        List<Grid> GridListWithButtons;

        public Settings0(ref VirtualDevice device)
        {
            InitializeComponent();
            Device=device;
            CreateFunction2CommandDict();
            PopulateButtonList();
            ApplyColor();
        }

        void PopulateButtonList()
        {
            GridListWithButtons =new List<Grid>();
            GridListWithButtons.Add(this.buttonGridGain);
            GridListWithButtons.Add(this.buttonGridOffset);
            GridListWithButtons.Add(this.buttonGridFrequency);
            GridListWithButtons.Add(this.buttonGridCurrent);
            GridListWithButtons.Add(this.buttonGridSettlingTime);
            GridListWithButtons.Add(this.buttonGridImageRate);

            ButtonList = new List<Button>();

            for (int i = 0; i < GridListWithButtons.Count; i++)
            {
                for (int j = 0; j < GridListWithButtons[i].Children.Count; j++)
                {
                    ButtonList.Add((Button)GridListWithButtons[i].Children[j]);
                }
            }
        }
        void ButtonPressedAction(ref object obj, string CallingMethodeName)
        {
            Button b=(Button)obj;
            
            b.MoveFocus(new TraversalRequest(new FocusNavigationDirection()));

            List<string> list = new List<string>(dic.Keys);
            
            string value= GetValueFromMethodeName(CallingMethodeName);

            string cmd="no command";
            for (int i = 0; i < list.Count; i++)
            {
                if (CallingMethodeName.Contains(list[i]))
                {
                    dic.TryGetValue(list[i], out cmd);
                }

            }

            bool dothis = true;
            string s = GetKeyFromMethodeName(CallingMethodeName);
            string valueToPrgm = "";
            switch (s)
            {
                case "Gain0":
                    valueToPrgm = value;
                    break;
                case "Gain1":
                    valueToPrgm = value;
                    break;
                case "Current":
                    valueToPrgm = CalculateCurrentFrommA(value).ToString();
                    break;
                case "Frequency":
                    
                    int tempint = FrequencyToValue(Convert.ToDouble(value));
                    valueToPrgm = tempint.ToString();
                    ParamManager.ProgramParameterByName("CurrentParameter.txt", "NCO_F", valueToPrgm, ref Device);
                    break;
                case "IRate":
                    valueToPrgm = value;
                    break;
                case "STime":
                    valueToPrgm = value;
                    break;
                case "Offset":
                    dothis = false;
                    valueToPrgm = OffsetI2Value(Convert.ToInt32(value), 32);
                    ParamManager.ProgramParameterByName("CurrentParameter.txt", "ST_IDTA", valueToPrgm, ref Device);
                    valueToPrgm = OffsetM2Value(Convert.ToInt32(value), 32);
                    ParamManager.ProgramParameterByName("CurrentParameter.txt", "ST_MDTA", valueToPrgm, ref Device);
                    break;
            }
            if (dothis)
            {
                ParamManager.ProgramParameterByName("CurrentParameter.txt", cmd, valueToPrgm, ref Device);
            }
            ParamManager.ProgramParameter("CurrentParameter.txt", ref Device);
            Device.StopAndStart();
            ApplyColor();
            //this.OK.Focus(); //to avoid focus style on the focus owner
    }
        int ValueToFrequency(double value)
        {
            int tempminindex = 0;
            double temp_mindiff_value=100000000000;
            for (int i = 0; i < 20; i++)
            {
                double temp_min_value=Math.Abs(((i * 10000) + 50000) - (value * 100.0 * 1e6 / Math.Pow(2, 32)));
                if (temp_min_value < temp_mindiff_value)
                {
                    temp_mindiff_value = temp_min_value;
                    tempminindex = i;
                }
            }
            return tempminindex;
        }
        int FrequencyToValue(double value)
        {
            return (int)(((value*10000)+50000) * Math.Pow(2, 32) / (100.0 * 1e6));
        }
        double CalculateCurrentFrommA(string s)
        {
            string sFloat = s;
            if (s[0] == '0')
            {
                sFloat=s.Insert(1, ".");
            }
            double mA = Convert.ToDouble(sFloat);
            double vref = 4.096;
            double r = Device.CurrentSourceSettings;//resitor R54
            double current = 256.0 * r * (mA / 1000.0) / vref;
            return Math.Round(current, 0);
        }
        
        string CalculateCurrentmAFromValue(double value)
        {
            double vref = 4.096;
            double r = Device.CurrentSourceSettings;//resitor R54
            double ma=value *1000.0*vref/(r*256.0);

            ma = Math.Round(ma, 1);
            if (ma < 1)
            {
                string temp ="0"+ ma.ToString().Substring(2);
                return temp;
            }
            else
            {
                ma = Math.Round(ma, 0);
                return ma.ToString();
            }
        }

        string OffsetI2Value(double offset, int NumberElectrode)
        {
            string output = "";
            string cmd;
            for(int i=0; i<NumberElectrode;i++)
            {
                if (i == 0)
                {
                    cmd = "I";
                }
                else if (i == (NumberElectrode-offset-1))
                {
                    cmd = "G";
                }
                else
                {
                    cmd= "N";
                }
                output = output + cmd;
            }
            return output;
        }
        string OffsetM2Value(double offset, int NumberElectrode)
        {
            string output = "";
            string cmd;
            for (int i = 0; i < NumberElectrode; i++)
            {
                if (i == 0)
                {
                    cmd = "1";
                }
                else if (i == (NumberElectrode - offset - 1))
                {
                    cmd = "2";
                }
                else
                {
                    cmd = "N";
                }
                output = output + cmd;
            }
            return output;
        }
        int Value2Offset(string value)
        {
            int NumberElectrode = value.Length;
            int offset=-1;
            if (value[0] != 'N')
            {
                switch(value[0])
                {
                    case '1':
                        offset=NumberElectrode-1-value.IndexOf('2');
                        break;
                    case 'I':
                        offset = NumberElectrode - 1 - value.IndexOf('G');
                        break;
                    case '2':
                        offset = NumberElectrode - 1 - value.IndexOf('1');
                        break;
                    case 'G':
                        offset = NumberElectrode - 1 - value.IndexOf('I');
                        break;
                }
            }
            
            return offset;
        }
        void ApplyColor()
        {
            ButtonColorList = new List<Button>();
            List<string> listK = new List<string>(dic.Keys);
            List<string> listV = new List<string>(dic.Values);

            List<int> ButtonGridColorIndex= new List<int>();

            string [] s=ParamManager.Read("CurrentParameter.txt");
            for (int i = 0; i < s.Length; i++)
            {
                for (int k = 0; k < listV.Count; k++)
                {
                    if (s[i].Contains(listV[k]))
                    {
                        string[] temp = s[i].Split(' ');
                        string buttonValue = "";
                        switch (listK[k])
                        {
                            case "Gain0":
                                buttonValue = temp[1];
                                break;
                            case "Gain1":
                                buttonValue = temp[1];
                                break;
                            case "Current":
                                buttonValue = CalculateCurrentmAFromValue(Convert.ToDouble(temp[1]));
                                break;
                            case "Frequency":
                                buttonValue = ValueToFrequency(Convert.ToDouble(temp[1])).ToString();
                                break;
                            case "IRate":
                                buttonValue = temp[1];
                                break;
                            case "STime":
                                buttonValue = temp[1];
                                break;
                            case "Offset":
                                buttonValue = Value2Offset(temp[1]).ToString();
                                break;
                        }
                        string ButtonName = "button" + listK[k] + "_" + buttonValue;
                        for (int j = 0; j < ButtonList.Count; j++)
                        {
                            if (ButtonList[j].Name == ButtonName)
                            {
                                ButtonColorList.Add(ButtonList[j]);
                            }
                        }
                    }
                }
            }

            for (int i = 0; i < ButtonList.Count; i++)
            {
                ButtonList[i].ClearValue(Button.BackgroundProperty);
                ButtonList[i].Focusable = false;
            }

            for (int i = 0; i < ButtonColorList.Count; i++)
            {
                ButtonColorList[i].Background = Brushes.Orange;
            }

            UpdateLabels();
        }


        void UpdateLabels()
        {
            string lCurrent="Current [mA]: ";
            string lDTime="Demodulation time [us]: ";
            string lSTime="Settling time [us]: ";
            string lMTime="Measurement time [us]: ";
            string lIRate = "Image Rate [i/s]: ";

            double dtime = Math.Round((Device.MeasurementTime-Device.SettlingTime)*1e6,3);
            double mtime = Math.Round(Device.MeasurementTime * 1e6,3);
            double stime = Math.Round(Device.SettlingTime * 1e6,3);
            double current = Math.Round(Device.ToVoltParameter.CurrentA * 1e3,3);
            double irate = Math.Round(1 / (Device.MeasurementTime * Device.NumberElectrode * Device.NumberElectrode), 3);

            labelCurrent.Content = lCurrent + current.ToString();
            labelDTime.Content = lDTime + dtime.ToString();
            labelSTime.Content = lSTime + stime.ToString();
            labelMTime.Content = lMTime + mtime.ToString();
            labelIRate.Content = lIRate + irate.ToString();
        }
        void CreateFunction2CommandDict()
        {
            dic = new Dictionary<string, string>();
            dic.Add("Gain0", "PGA0_G");
            dic.Add("Gain1", "PGA1_G");
            dic.Add("Current", "DAC_G");
            dic.Add("Offset", "ST_IDTA");
            dic.Add("Frequency", "NCO_F");
            dic.Add("IRate", "#imagerate");
            dic.Add("STime", "#settlingtime");
            dic.Add("NElectrode", "#numberelectrode");
        }

        string GetValueFromMethodeName(string Name)
        {
            string [] s =Name.Split('_');
            return s[1];
        }

        string GetKeyFromMethodeName(string Name)
        {
            string[] s = Name.Split('_');
            string output = s[0].Replace("button","");
            return output;
        }

        private void buttongrid_Loaded(object sender, RoutedEventArgs e)
        {
            //ApplyColor();
        }

        #region GainEvents
        private void buttonGain0_0_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonGain0_1_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonGain1_0_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonGain1_1_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonGain1_2_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonGain1_3_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonGain1_4_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonGain1_5_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonGain1_6_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }
        #endregion
        #region CurrentEvents
        private void buttonCurrent_05_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonCurrent_1_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonCurrent_2_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonCurrent_3_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonCurrent_4_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonCurrent_5_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonCurrent_6_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonCurrent_7_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonCurrent_8_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonCurrent_10_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        #endregion
        #region OffsetEvents
        private void buttonOffset_0_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonOffset_1_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonOffset_2_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonOffset_3_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonOffset_4_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonOffset_5_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonOffset_15_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonOffset_6_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonOffset_7_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonOffset_9_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonOffset_8_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonOffset_10_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonOffset_11_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonOffset_12_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonOffset_13_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonOffset_14_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }
        #endregion
        #region frequency
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }
        private void buttonFrequency_0_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }
        private void buttonFrequency_1_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonFrequency_2_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonFrequency_3_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonFrequency_4_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonFrequency_5_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonFrequency_6_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonFrequency_7_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonFrequency_8_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonFrequency_9_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonFrequency_10_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonFrequency_11_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonFrequency_12_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonFrequency_13_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonFrequency_14_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonFrequency_15_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonFrequency_16_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonFrequency_17_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonFrequency_18_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonFrequency_19_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonFrequency_20_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        #endregion
        #region ImageRate
        private void buttonIRate_1_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonIRate_10_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonIRate_20_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonIRate_30_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonIRate_40_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonIRate_50_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }
        #endregion
        #region SettlingTime
        private void buttonSTime_0_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonSTime_10_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonSTime_20_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonSTime_30_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonSTime_40_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }

        private void buttonSTime_50_Click(object sender, RoutedEventArgs e)
        {
            ButtonPressedAction(ref sender, MethodInfo.GetCurrentMethod().Name);
        }
        #endregion

        private void OK_Click(object sender, RoutedEventArgs e)
        {
            Window window = Window.GetWindow(this);
            if (window != null)
                window.Close(); 
        }

    }
}
